package com.softstao.guoyu.mvp.interactor;

import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;

import com.kymjs.rxvolley.RxVolley;
import com.kymjs.rxvolley.client.HttpCallback;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UpProgressHandler;
import com.qiniu.android.storage.UploadManager;
import com.qiniu.android.storage.UploadOptions;
import com.softstao.guoyu.global.APIInterface;
import com.softstao.guoyu.global.GYApplication;
import com.softstao.guoyu.mvp.api.CustomRxVolley;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import rx.functions.Action1;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * Created by xuhon on 2016/9/5.
 */
public class UploadInteractor extends BaseInteractor {
    private String BASE_URL = "http://gyimage.giocosoholdings.com";
    public static String TOKEN;
    public static String KEY = "gy-image";
    public void uploadFile(View uploadProgress,File localFile , Action1<Object> action1){
        Luban.with(GYApplication.application)
                .load(localFile)
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {
                    }

                    @Override
                    public void onSuccess(File file) {
                        UploadManager uploadManager = new UploadManager();
                        final Map<String, Object> paramsMap = new HashMap<>();
                        int dot = localFile.getName().lastIndexOf('.');
                        String fileName = System.currentTimeMillis() + "." + (dot>-1?localFile.getName().substring(dot+1):"jpg");
                        paramsMap.put("x:image", fileName);
                        UpProgressHandler progressListener = (key, percent) -> {
                            {
                                if(uploadProgress!=null&&uploadProgress instanceof ProgressBar){
                                    ((ProgressBar)uploadProgress).setProgress((int) (percent*1000));
                                }
                            }
                        };
                        //结束回调，不可为空
                        UpCompletionHandler completeListener = (key, info, response) -> {
                            {
                                if (info.isOK()==true){
                                    try {
                                        JSONObject jsonObject = new JSONObject(response.toString());
                                        if (key!=null){
                                            action1.call(BASE_URL + "/" + key);
                                        }else {
                                            action1.call(BASE_URL + "/" + jsonObject.opt("key"));
                                        }
                                        if(uploadProgress!=null){
                                            uploadProgress.setVisibility(View.GONE);
                                        }
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }else{
                                    Log.e("UploadFile",key);
                                }
                            }
                        };

                        UploadOptions uploadOptions = new UploadOptions(null,null,false,progressListener,null);
                        new CustomRxVolley.Builder().httpMethod(RxVolley.Method.GET)
                                .url(APIInterface.API_SERVER + "upload/uploadToken")
                                .contentType(RxVolley.ContentType.FORM)
                                .callback(new HttpCallback() {
                                    @Override
                                    public void onSuccess(Map<String, String> headers, byte[] t) {
                                        super.onSuccess(headers, t);
                                        String json = new String(t);
                                        try {
                                            JSONObject jsonObject = new JSONObject(json);
                                            TOKEN = jsonObject.optString("upToken");
                                            uploadManager.put(file,fileName,TOKEN,completeListener,uploadOptions);
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                    }

                                    @Override
                                    public void onFailure(int errorNo, String strMsg) {
                                        super.onFailure(errorNo, strMsg);
                                    }
                                }).doTask();
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }
                }).launch();
    }

    public void uploadFileForTarget(View uploadProgress,String tag,File localFile , Action1<Object> action1){
        Luban.with(GYApplication.application)
                .load(localFile)
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {
                    }

                    @Override
                    public void onSuccess(File file) {
                        UploadManager uploadManager = new UploadManager();
                        final Map<String, String> paramsMap = new HashMap<>();
                        int dot = localFile.getName().lastIndexOf('.');
                        String fileName = System.currentTimeMillis() + "." + (dot>-1?localFile.getName().substring(dot+1):"jpg");
                        paramsMap.put("x:image", fileName);
                        UpProgressHandler progressListener = (key, percent) -> {
                            {
                                if(uploadProgress!=null&&uploadProgress instanceof ProgressBar){
                                    ((ProgressBar)uploadProgress).setProgress((int) (percent*1000));
                                }
                            }
                        };
                        //结束回调，不可为空
                        UpCompletionHandler completeListener = (key, info, response) -> {
                            {
                                if (info.isOK()==true){
                                    try {
                                        JSONObject jsonObject = new JSONObject(response.toString());
                                        if (key!=null) {
                                            action1.call(tag + "`" + BASE_URL + "/" + key);
                                        }else {
                                            action1.call(tag + "`" + BASE_URL + "/" + jsonObject.opt("key"));
                                        }
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }else{
                                    Log.e("UploadFile",info.error);
                                }
                            }
                        };

                        UploadOptions uploadOptions = new UploadOptions(paramsMap,null,false,progressListener,null);
                        new CustomRxVolley.Builder().httpMethod(RxVolley.Method.GET)
                                .url(APIInterface.API_SERVER + "upload/uploadToken")
                                .contentType(RxVolley.ContentType.FORM)
                                .callback(new HttpCallback() {
                                    @Override
                                    public void onSuccess(Map<String, String> headers, byte[] t) {
                                        super.onSuccess(headers, t);
                                        String json = new String(t);
                                        try {
                                            JSONObject jsonObject = new JSONObject(json);
                                            TOKEN = jsonObject.optString("upToken");
                                            uploadManager.put(file,fileName,TOKEN,completeListener,uploadOptions);
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                    }

                                    @Override
                                    public void onFailure(int errorNo, String strMsg) {
                                        super.onFailure(errorNo, strMsg);
                                    }
                                }).doTask();
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }
                }).launch();
    }
}
